/***************************************************************************
 *   Copyright (C) 2008 by JBox systems
 *   gabi@shaargiora.co.il
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the
 *   Free Software Foundation, Inc.,
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 ***************************************************************************/

#include <QMessageBox>
#include <QFileDialog>
#include <QFile>
#include <QIcon>
#include <QXmlInputSource>
#include <QDomElement>

#include <boost/filesystem.hpp>
#include <string>
#include <cstdlib>
#include <iostream>

#include "gui.h"
#include "appsmodel.h"
#include "utils.h"
#include "importhandler.h"
#include "logwatcher.h"
#include "download.h"
#include "const.h"

extern std::string path_to_database;

AutoMateUi::AutoMateUi(QWidget* parent) :
	QMainWindow(parent) {
	setupUi(this);
	actionsConnect();
	connectUi();
	AppsModel *amodel = new AppsModel(loadApplicationDatabase((boost::filesystem::path(path_to_database) / "applications").string().c_str()));
	apps_view->setModel(amodel);

	// Watch log file
	logWatcher = new TailWatch(LOGFILE, log_browser);
}

void AutoMateUi::setupUi(QMainWindow *widget) {
	Ui::AutoMate::setupUi(widget);

	// Add search to toolbar
	//TODO in version 0.2
	// 	searchEdit = new QLineEdit(this);
	// 	toolBar->addWidget(searchEdit);

	// Add progress bar to status bar
	downloadProgressBar = new QProgressBar(this);
	statusBar()->addPermanentWidget(downloadProgressBar);
	downloadProgressBar->hide();
}

void AutoMateUi::connectUi() {
	connect(clear_log_button, SIGNAL(clicked()), log_browser, SLOT(clear()));
}

void AutoMateUi::actionsConnect() {
	connect(actionAbout ,SIGNAL( triggered(bool) ), this, SLOT( about() ) );
	connect(actionNew ,SIGNAL( triggered(bool) ), this, SLOT( clearApps() ) );
	connect(actionApply ,SIGNAL( triggered(bool) ), this, SLOT( install() ) );
	connect(actionLoad ,SIGNAL( triggered(bool) ), this, SLOT( load() ) );
	connect(actionSave ,SIGNAL( triggered(bool) ), this, SLOT( save() ) );
	connect(actionDownload ,SIGNAL( triggered(bool) ), this, SLOT( download() ) );
}

void AutoMateUi::quit() {
}

void AutoMateUi::about(){
	QMessageBox::about(this, "About Auto-Mate", "<center><b>Auto-Mate</b></center>\nAutomates installing applications and performing other actions. A GUI front-end for an application and settings database.");
}

void AutoMateUi::save() {
	std::vector<Version> vers = static_cast<AppsModel*>(apps_view->model())->getSelected();
	QDomDocument doc("export");
	QDomElement root = doc.createElement("template");
	doc.appendChild(root);
	for(std::vector<Version>::iterator itr = vers.begin(); itr != vers.end(); ++itr)
	{
		QDomElement inst = doc.createElement("install");
		if (! itr->is_last)
			inst.setAttribute("version",itr->version().c_str());
		QDomText name = doc.createTextNode(itr->name().c_str());
		inst.appendChild(name);
		root.appendChild(inst);
	}
	QString flname = QFileDialog::getSaveFileName(this,"Select a destination to export...", "", "XML files(*.xml)");
	QFile *fl = new QFile(flname);
	if (!fl->open(QIODevice::WriteOnly | QIODevice::Text)) {
		statusBar()->showMessage("Writing to file failed..", 3000);
		return;
	}
	fl->write(doc.toString().toLocal8Bit());
	fl->close();
	statusBar()->showMessage("Exported..", 3000);
}

void AutoMateUi::load() {
	QString flname = QFileDialog::getOpenFileName(this,"Select a file to import...", "", "XML files(*.xml)");
	if(flname == "")
	{
		statusBar()->showMessage("Importing failed...", 3000);
		return;
	}
	ImportHandler *handler = new ImportHandler;
	QFile *fl = new QFile(flname);
	QXmlInputSource *src = new QXmlInputSource(fl);
	QXmlSimpleReader *reader = new QXmlSimpleReader;
	reader->setContentHandler(handler);
	reader->parse(src);
	std::vector<QModelIndex> toExpand = static_cast<AppsModel*>(apps_view->model())->setSelected(handler->installList());
	for (unsigned int i = 0; i < toExpand.size(); ++i) {
		apps_view->expand(toExpand[i]);
	}
	apps_view->repaint();;
}

void AutoMateUi::clearApps() {
	static_cast<Model*>(apps_view->model())->clearSelection();
	apps_view->repaint();;
}

void AutoMateUi::clearTweaks() {

}

void AutoMateUi::install() {
	AppsModel* model = static_cast<AppsModel*>(apps_view->model());
	std::vector<Version> apps = model->getSelected();
	std::vector<Version>::iterator apps_itr = apps.begin();
	while(apps_itr != apps.end())
	{
		Version version = *apps_itr++;
		statusBar()->showMessage((std::string("Proceeding to install ") + version.name() + " " + version.version() + "...").c_str(), 3000);
		installer.install(version);
		statusBar()->showMessage("Installer finished with exit code: " + QString::number(installer.lastCode()), 3000);
	}
	clearApps();
}

void AutoMateUi::tweak() {

}

void AutoMateUi::download() {
	std::vector<Version> versions; // List of application versions to download
	std::vector<Version> selected = static_cast<AppsModel*>(apps_view->model())->getSelected();

	// If nothing selected, select the last versions of all applications
	if (selected.size() == 0)
		selected = static_cast<AppsModel*>(apps_view->model())->getLastVersions();

	// Get version objects of versions to download
	for (std::vector<Version>::iterator itr = selected.begin(); itr != selected.end(); ++itr) {
		if (itr->url().size())
			versions.push_back(*itr);
	}

	// Nothing to download
	if (versions.size() == 0)
		return;

	// Change the download action to a "stop download" action.
	actionDownload->setText("Stop download");
	actionDownload->setIcon(QIcon(QPixmap(":/icons/abort.png")));
	disconnect(actionDownload, 0, this, 0);
	connect(actionDownload ,SIGNAL(triggered(bool)), this, SIGNAL(abortDownloads()));
	downloadProgressBar->show();
	emit downloadVersions(versions);
}

void AutoMateUi::updateDataReadProgress(int bytesRead, int totalBytes){
	downloadProgressBar->setMaximum(totalBytes);
	downloadProgressBar->setValue(bytesRead);
}

void AutoMateUi::resetDownloadAction() {
	actionDownload->setText("Download");
	actionDownload->setIcon(QIcon(QPixmap(":/icons/download.png")));
	statusBar()->showMessage("");
	downloadProgressBar->reset();
	downloadProgressBar->hide();
	disconnect(actionDownload, 0, this, 0);
	connect(actionDownload ,SIGNAL(triggered(bool)), this, SLOT(download()));
}

void AutoMateUi::updateStatusMessage(QString message) {
	statusBar()->showMessage(message);
}
